<template>
    <div>
        <div class="container">
            <div class="handle-box">
                <el-form :model="query" ref="queryForm" :inline="true" label-width="68px">
                    <el-form-item label="账号" prop="name">
                        <el-input v-model="query.account" placeholder="账号" size="mini" class="handle-input mr10"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="cyan" icon="el-icon-search"  size="mini" @click="handleSearch">搜索</el-button>
                    </el-form-item>
                </el-form>
                <div>
                    <el-row :gutter="10" class="mb8 el-form-item">
                        <el-col :span="1.5">
                            <el-button type="primary" icon="el-icon-plus" class="handle-del floatr"  size="mini" @click="addSysRole">新增</el-button>
                        </el-col>
                    </el-row>
                </div>
            </div>
            <el-table
                    :data="tableData"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column type="index" label="ID" width="55" align="center" ></el-table-column>
                <el-table-column prop="account" label="账号"></el-table-column>
                <el-table-column prop="username" label="用户名"></el-table-column>
                <el-table-column prop="post" label="职务"></el-table-column>
                <el-table-column prop="mobile" label="联系方式"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="rolenames" label="角色"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                                type="text"
                                icon="el-icon-delete"
                                class="red"
                                @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                        <el-button
                                type="text"
                                icon="el-icon-mouse"
                                @click="enableAndDisable(scope.$index, scope.row)"
                        >{{scope.row.status === 0 ? '禁用' : '启用'}}</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="query.pageIndex"
                        :page-size="query.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :model="form"   :rules="rules" label-width="100px">
                <el-form-item label="账号" prop="account">
                    <el-input maxlength="20" v-model="form.account" ></el-input>
                </el-form-item>
                <el-form-item label="图片">
                    <div>
                        <el-upload  style="display:inline-block;"
                                    class="avatar-uploader"
                                    :action="$setting.baseURL + '/file/upload'"
                                    :headers="fileHeaders"
                                     multiple
                                    :show-file-list="false"
                                    accept=".jpg,.jpeg,.png,.JPG,.JPEG"
                                    :on-success="handleSuccessOther"
                                    :before-upload="beforeAvatarUpload">
                            <img v-if="form.headUrl != '' " :src="$setting.baseImgUrl+form.headUrl" style="width:140px;height:140px">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                        <div style="display:inline-block;height:70px;overflow:hidden;vertical-align:top;color:red;">
                            建议图片尺寸（宽：140 高：140）
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="密码" prop="password" v-if="addType">
                    <el-input maxlength="20" v-model="form.password" ></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="newPassword" v-if="addType">
                    <el-input maxlength="20" v-model="form.newPassword" ></el-input>
                </el-form-item>
                <el-form-item label="用户名" prop="username">
                    <el-input maxlength="20" v-model="form.username" ></el-input>
                </el-form-item>
                <el-form-item label="联系方式" prop="mobile">
                    <el-input maxlength="20" v-model="form.mobile" ></el-input>
                </el-form-item>
                <el-form-item label="职务">
                    <el-input maxlength="20" v-model="form.post" ></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input maxlength="20" v-model="form.email" ></el-input>
                </el-form-item>
                <el-form-item label="菜单权限">
                    <el-checkbox-group v-model="form.role">
                        <el-checkbox v-for="(item, index) in roleList" :label="item.id" :value="item.id" name="menu">{{item.roleName}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="butCancel">取 消</el-button>
                <el-button type="primary" @click="saveEdit('form')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import sysUser from '../../api/sysUser';
    export default {
        name: 'basetable',
        data() {
            return {
                query: {
                    account: '',
                    status:'',
                    id:'',
                    version:'',
                    pageIndex: 1,
                    pageSize: 10
                },
                 //文件上传
                fileHeaders: {
                    'X-Token': localStorage.getItem("X-Token")
                },
                tableData: [],
                multipleSelection: [],
                roleList:[],
                delList: [],
                editVisible: false,
                pageTotal: 0,
                form: {
                    account:"",
                    username:"",
                    post:"",
                    mobile:"",
                    email:"",
                    rolenames:"",
                    password:"",
                    newPassword:"",
                    role:[]
                },
                rules:{
                    account :[{required: true, message: '账号不能为空', trigger: 'blur'}],
                    username :[{required: true, message: '用户名不能为空', trigger: 'blur'}],
                    mobile :[{required: true, message: '联系方式不能为空', trigger: 'blur'}],
                    password :[{required: true, message: '密码不能为空', trigger: 'blur'}],
                    newPassword :[{required: true, message: '确认密码不能为空', trigger: 'blur'}],
                },
                idx: -1,
                id: -1,
                addType:false,
            };
        },
        created() {
            this.getData();
        },
        filters:{
            //格式化后台传过来的时间戳
            dateFormat(time) {
                let date = new Date(time);
                return vue.$tool._dateFormat(date,'yyyy-MM-dd hh:mm')
            }
        },
        methods: {
            // 获取list
            getData() {
                sysUser.selectList(this.query).then(res => {
                    this.tableData = res.data.items;
                    this.pageTotal = res.data.total || 50;
                });
            },
            // 获取菜单list
            getRoleList(id){
                var _that =this;
                sysUser.sysRoleList({}).then(res => {
                    _that.roleList = res.data.items;
                    if(id != "" && id != null){
                        sysUser.getUserRole(id).then(res1 => {
                            for (var i = 0; i < res1.data.items.length; i++) {
                                for (var j = 0; j < _that.roleList.length; j++) {
                                    if (_that.roleList[j].id == res1.data.items[i].roleId) {
                                        _that.form.role.push(res1.data.items[i].roleId);
                                        break;
                                    }
                                }
                            }
                        });
                    }
                });
            },
            // 查询角色
            selectSysUserOne(id){
                var _that =this;
                sysUser.selectSysUser(id).then(res => {
                    _that.form = res.data;
                    if(_that.form.role == null){
                        _that.form.role = [];
                    }
                    this.getRoleList(id)
                });
            },
            // 触发搜索按钮
            handleSearch() {
                this.$set(this.query, 'pageIndex', 1);
                this.getData();
            },
            // 删除操作
            handleDelete(index, row) {
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.query.status = 1 ;
                    this.query.id = row.id ;
                    this.query.version = row.version ;
                    sysUser.delSysUser(this.query).then(res => {
                        this.$message.success('删除成功');
                        this.getData();
                    });
                })
                .catch(() => {});
            },
            // 启用禁用
            enableAndDisable(index, row) {
                var param ={}
                var title = "启用";
                if(row.status === 0){
                    title = "禁用"
                }
                this.$confirm('确定要'+title+'吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    param.status = row.status === 0 ? 2 : 0 ; // 2禁用
                    param.id = row.id ;
                    param.version = row.version ;
                    sysUser.enableAndDisable(param).then(res => {
                        this.$message.success(title+'成功');
                        this.getData();
                    });
                })
                    .catch(() => {});
            },
            // 多选操作
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 编辑操作
            handleEdit(index, row) {
                this.idx = index;
                this.editVisible = true;
                this.addType = false;
                this.selectSysUserOne(row.id)
            },
            //新增操作
            addSysRole() {
                vue.$tool.resetForm(this.form);
                this.addType = true;
                this.editVisible = true;
                this.getRoleList()
            },
            // 保存编辑
            saveEdit(formData) {
                this.$refs[formData].validate((valid) => {
                    if (valid) {
                        if(this.form.id != null && this.form.id != undefined){
                            // 编辑
                            sysUser.updateSysUser(this.form).then(res => {
                                this.$message.success("保存成功");
                                this.getData();
                            });
                        }else{
                            // 新增
                            sysUser.addSysUser(this.form).then(res => {
                                this.$message.success("保存成功");
                                this.getData();
                            });
                        }
                    }
                })
            },
            butCancel(){
                this.editVisible = false;
                vue.$tool.resetForm(this.form);
            },
            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'pageIndex', val);
                this.getData();
            },
            handleSuccessOther(response, file, fileList) {
                this.form.headUrl = response.data.path;
            },
            // 校验图片上传
            beforeAvatarUpload(file) {
            }
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }
    .table {
        width: 100%;
        font-size: 14px;
    }
    .red {
        color: #ff0000;
    }
    .mr10 {
        margin-right: 10px;
    }
    .floatr {
        float: right;
    }
    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }
</style>
